package com.chinacoal.hr.levelimpl.service.impl;

import com.chinacoal.hr.levelapi.entity.AttendanceInfoTemp;
import com.chinacoal.hr.levelapi.entity.Employee;
import com.chinacoal.hr.levelimpl.client.AttendanceWebClient;
import com.chinacoal.hr.levelimpl.dao.AttendanceInfoTempDao;
import com.chinacoal.hr.levelimpl.service.AttendanceInfoTempService;
import com.chinacoal.hr.levelimpl.service.EmployeeService;
import com.chinacoal.hr.levelimpl.utils.DateUtil;
import com.chinacoal.hr.levelimpl.utils.StaticDicts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: YunTao.Li
 * @create: 2019-12-22 17:49
 * @description:
 **/
@Service
public class AttendanceInfoTempServiceImpl implements AttendanceInfoTempService {

    @Autowired
    private AttendanceInfoTempDao attendanceInfoTempDao;

    @Autowired
    private AttendanceWebClient attendanceWebClient;

    @Autowired
    private EmployeeService employeeService;


    /**
     * 从接口获得考勤信息明细，同步到考勤信息临时表
     *
     * @param beginDateStr :yyyyMMdd
     * @param endDateStr   :yyyyMMdd
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author : YunTao.Li
     * @date : 2019/12/22 2019/12/22
     */
    @Override
    @Transactional
    public List<AttendanceInfoTemp> syncAttendanceInfoTemp(String beginDateStr, String endDateStr) throws Throwable {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        // step1 : 清空考勤临时表
        this.attendanceInfoTempDao.clearAttendanceInfoTemp();

        // step2 : 从webservice接口获得考勤临时数据
        List<AttendanceInfoTemp> attendanceInfoTemps = attendanceWebClient.attendanceDetailSyncLoader(beginDateStr, endDateStr);

        // 生成随机的session id
        int hashCodev = UUID.randomUUID().toString().hashCode();
        if (hashCodev < 0) {
            hashCodev = -hashCodev;
        }
        String seesionID = "SYNC" + String.format("%015d", hashCodev);


        // step3 : 获得所有开发公司人员以及应考勤记录
        Map condition239 = new HashMap();
        condition239.put("orgId", "239");
        Map condition261 = new HashMap();
        condition261.put("orgId", "261");
        List<Employee> employees239 = employeeService.getEmployeeListWithOutPage(condition239); // 开发公司人员
        List<Employee> employees261 = employeeService.getEmployeeListWithOutPage(condition261); // 咨询公司人员

        List<Employee> employees = new ArrayList<>();
        employees.addAll(employees239);
        employees.addAll(employees261);

        Date beginDate = dateFormat.parse(beginDateStr);
        Date endDate = dateFormat.parse(endDateStr);
        Date date = new Date();

        if (DateUtil.dateCompareTo(endDate, date) >= 0) {
            endDate = date;
        }

        int dayCount = DateUtil.getNatureDayMargin(beginDate, endDate);
        Map empDateMap = new HashMap();

        /**
         * 整理需要补全考勤数据的日期集合
         *
         * key : empcode + 20200722
         * value : employee {empid:,empname,...}
         * */
        for (int i = 0; i < dayCount; i++) {
            // 从开始日期机算，
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(beginDate);
            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + i - 1);

            // 计算日期，当前天
            Date currentDate = calendar.getTime();
            String currentDateStr = dateFormat.format(currentDate);

            //如果是假期则跳过不补全
            if (DateUtil.getInstance().isHoliday(currentDate)) {
                continue;
            }

            for (Employee emp : employees) {
                String empCode = emp.getEmpCode();

                String key = empCode + "-" + currentDateStr;
                empDateMap.put(key, emp);
            }
        }

        // step4 : 遍历插入考勤临时明细
        for (int i = 0; i < attendanceInfoTemps.size(); i++) {
            AttendanceInfoTemp attendanceInfoTemp = attendanceInfoTemps.get(i);
            attendanceInfoTemp.setSessionId(seesionID);
            attendanceInfoTemp.setStartDate(830); // 应到时间
            attendanceInfoTemp.setEndDate(1700); // 应退时间

            String empCode = attendanceInfoTemp.getEmpCode();
            if (("10010786").equals(empCode)) {
                System.out.println(1);
            }
            String attendDateStr = dateFormat.format(attendanceInfoTemp.getAttendDate());


            String key = empCode + "-" + attendDateStr;

            if (empDateMap.containsKey(key)) {

                Employee emp = (Employee) empDateMap.get(key);
                String isAttendance = emp.getIsAttendance();
                empDateMap.remove(key);
                if (("0").equals(isAttendance)) {
                    continue;
                }
            }

            this.attendanceInfoTempDao.insertAttendanceInfoTemp(attendanceInfoTemp);
        }

        // step4 : 补全考勤临时明细
        empDateMap.forEach((k, v) -> {
            try {
                String empCode = k.toString().split("-")[0];
                String attendDateStr = k.toString().split("-")[1];
                Employee emp = (Employee) v;
                String isAttendance = emp.getIsAttendance();
                if (("0").equals(isAttendance)) {
                    return;
                }
                if (("10010786").equals(empCode)) {
                    System.out.println(1);
                }

                AttendanceInfoTemp attendanceInfoTemp = new AttendanceInfoTemp();
                attendanceInfoTemp.setSessionId(seesionID);
                attendanceInfoTemp.setStartDate(830); // 应到时间
                attendanceInfoTemp.setEndDate(1700); // 应退时间
                attendanceInfoTemp.setSignOutAddr("");//签退地点
                attendanceInfoTemp.setSignUp(0);//签到时间
                attendanceInfoTemp.setEmpName(emp.getEmpName());//员工姓名
                attendanceInfoTemp.setSignOutStatus(StaticDicts.SIGN_STATUS_MISSING);//签退状态
                attendanceInfoTemp.setSignOut(0);//签退时间
                attendanceInfoTemp.setEmpCode(emp.getEmpCode());//员工编码
                attendanceInfoTemp.setSignUpAddr("");//签到地点
                attendanceInfoTemp.setSignUpInfo("考勤系统自动补漏签");//签到备注
                attendanceInfoTemp.setSignUpStatus(StaticDicts.SIGN_STATUS_MISSING);//签到状态
                attendanceInfoTemp.setOrgName(emp.getOrgName());//组织名称
                Date attendDate = new SimpleDateFormat("yyyyMMdd").parse(attendDateStr);
                String weekStr = new SimpleDateFormat("EEEE").format(attendDate);
                attendanceInfoTemp.setWeekDay(weekStr);
                attendanceInfoTemp.setAttendDate(attendDate);//考勤日期
                attendanceInfoTemp.setDeptName(emp.getDeptName());//部门名称
                attendanceInfoTemp.setSignOutInfo("考勤系统自动补漏签"); //签退备注
                this.attendanceInfoTempDao.insertAttendanceInfoTemp(attendanceInfoTemp);

                attendanceInfoTemps.add(attendanceInfoTemp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        return attendanceInfoTemps;
    }

    /**
     * 根据SESSIONID 获得同步回来的临时考勤记录
     *
     * @param sessionId :
     * @return : java.util.List<com.chinacoal.hr.levelimpl.entity.AttendanceInfoTemp>
     * @author : YunTao.Li
     * @date : 2019/12/26 2019/12/26
     */
    @Override
    public List<AttendanceInfoTemp> getAttendanceInfoTempBySessionID(String sessionId) throws Throwable {
        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("sessionId", sessionId);

        List<AttendanceInfoTemp> attendanceInfoTemps = this.attendanceInfoTempDao.getAttendanceInfoTemps(condition);
        return attendanceInfoTemps;
    }
}
